<script setup lang="ts">
import { getArticleDetailAPI, articleOptAPI, type ArticleRowItem } from '@/apis/article'
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { showToast } from 'vant'

const route = useRoute()
const id = route.params.id
const article = ref<ArticleRowItem>()
const getArticleDetail = async () => {
  const res = await getArticleDetailAPI(id as string)
  article.value = res.data
}
getArticleDetail()

// 处理收藏功能
const handleCollect = async () => {
  if (!article.value) return
  const newCollectFlag = article.value.collectFlag === 1 ? 0 : 1
  try {
    await articleOptAPI({
      id: article.value.id,
      optType: 2, // 2表示收藏操作
    })
    article.value.collectFlag = newCollectFlag
    showToast(newCollectFlag === 1 ? '收藏成功' : '取消收藏')
  } catch (error) {
    showToast('操作失败，请重试' + error)
  }
}

// 处理点赞功能
const handleLike = async () => {
  if (!article.value) return
  const newLikeFlag = article.value.likeFlag === 1 ? 0 : 1
  const newLikeCount = article.value.likeCount + (newLikeFlag === 1 ? 1 : -1)
  try {
    await articleOptAPI({
      id: article.value.id,
      optType: 1, // 1表示点赞操作
    })
    article.value.likeFlag = newLikeFlag
    article.value.likeCount = newLikeCount
    showToast(newLikeFlag === 1 ? '点赞成功' : '取消点赞')
  } catch (error) {
    showToast('操作失败，请重试' + error)
  }
}
</script>
<template>
  <div class="detail-page">
    <van-nav-bar left-text="返回" left-arrow @click-left="$router.back()" fixed title="面经详情" />
    <header class="header">
      <h1>{{ article?.stem || '' }}</h1>
      <p>
        {{ article?.createdAt || '' }} | {{ article?.views || 0 }} 浏览量 |
        {{ article?.likeCount || 0 }} 点赞数
      </p>
      <p>
        <img src="http://teachoss.itheima.net/heimaQuestionMiniapp/官方默认头像%402x.png" alt="" />
        <span>{{ article?.creator || '' }}</span>
      </p>
    </header>

    <main class="body" v-html="article?.content || ''"></main>

    <div class="opt">
      <van-icon
        :class="{ active: article?.collectFlag === 1 }"
        name="star-o"
        @click="handleCollect"
      />
      <van-icon :class="{ active: article?.likeFlag === 1 }" name="like-o" @click="handleLike" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.detail-page {
  margin-top: 44px;
  overflow: hidden;
  padding: 0 15px;
  .header {
    h1 {
      font-size: 24px;
    }
    p {
      color: #999;
      font-size: 12px;
      display: flex;
      align-items: center;
    }
    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      overflow: hidden;
    }
  }
  .opt {
    position: fixed;
    bottom: 100px;
    right: 0;
    > .van-icon {
      margin-right: 20px;
      background: #fff;
      width: 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      border-radius: 50%;
      box-shadow: 2px 2px 10px #ccc;
      font-size: 18px;
      &.active {
        background: #fec635;
        color: #fff;
      }
    }
  }
}
</style>
